<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../vue.js"></script>
</head>

<body>
  <!-- 这段代码做到的效果是 子组件的数据是从根组件获取的, input框双向绑定子组件的数据, 并且能修改根组件的数据 -->
  <!-- 根组件模板 -->
  <div id="app">
    <!-- 根组件接收子组件发送的数据 并且监听一个从子组件接收数据的自定义事件 -->
    <cpn :number1="num1" :number2="num2" @changenum1="fatherchangnum1" @changenum2="fatherchangnum2"></cpn>
  </div>

  <!-- 子组件模板 -->
  <template id="cpn">
    <div>
      <!-- input双向绑定子组件的数据 并且绑定一个向父组件发送数据的事件 -->
      <input type="text" v-model="cpnnum1" @input="changenum1">
      <!-- number1 为根组件的数据 -->
      <h2>props: {{number1}}</h2>
      <!-- cpnnum1 为子组件的数据 -->
      <h2>data: {{cpnnum1}}</h2>
      <input type="text" v-model="cpnnum2" @input="changenum2">
      <h2>props: {{number2}}</h2>
      <h2>data: {{cpnnum2}}</h2>
    </div>
  </template>

  <script>
    const app = new Vue({
      el: "#app",
      data: {
        num1: 0,
        num2: 1
      },
      methods: {
        // 处理从子组件接收来的数据
        fatherchangnum1(newnum) {
          this.num1 = parseFloat(newnum)
        },
        fatherchangnum2(newnum) {
          this.num2 = parseFloat(newnum)
        }
      },
      components: {
        // 在根组件中 注册 子组件
        cpn: {
          template: '#cpn',
          // 向根组件 请求 数据
          props: {
            number1: {
              type: Number,
              required: true
            },
            number2: {
              type: Number,
              required: true
            }
          },
          data() {
            return {
              cpnnum1: this.number1,
              cpnnum2: this.number2
            }
          },
          methods: {
            // 向根组件发送数据
            changenum1() {
              this.$emit("changenum1", this.cpnnum1);
              this.cpnnum2 = this.cpnnum1 / 100;
              this.$emit("changenum2", this.cpnnum2)
            },
            changenum2() {
              this.$emit("changenum2", this.cpnnum2)
              this.cpnnum1 = this.cpnnum2 * 100;
              this.$emit("changenum1", this.cpnnum1)
            }
          }
        }
      }
    })
  </script>
</body>

</html>